package com.magicborrow.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpJsonRequest {

    /**
     * 通过拼接的方式构造请求内容，实现参数传输以及文件传输
     *
     * @param url
     * Service net address
     * @param params
     * text content
     * @param files
     * pictures
     * @return String result of Service response
     * @throws IOException
     */
    public static final double MAX_LEANTH = 100 * 1024;

    public static String jsonPost(String url, JSONObject params,
                                  Map<String, File> files) throws Exception {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(30 * 1000); // 缓存的最长时间
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
    /*	conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
                + ";boundary=" + BOUNDARY);*/
        conn.setRequestProperty("Content-Type", "application/x-javascript; charset=" + CHARSET);
        //	conn.setRequestProperty("Content-Length", String.valueOf(params.toString().getBytes(CHARSET).length));
        conn.setConnectTimeout(5 * 1000);
    /*	String token = "YG.USFood.ANDROID.AAAAB3NzaC1yc2EAAAABIwAAAQEAwEtF1hfvsOpIboYO01g1D0ZOVPm1p";
        String timestamp = System.currentTimeMillis() + "";
		Random rd = new Random();
		int ad = rd.nextInt(10000);
		String nonce = ad + "";
		String[] columns = new String[] { token, timestamp, nonce };
		Arrays.sort(columns);
		String singature = VolleyTool.convertSHA1(TextUtils.join("", columns));
		conn.setRequestProperty("YgUsFood", "signature=" + singature + "&timestamp="
				+ timestamp + "&nonce=" + nonce);*/


        DataOutputStream outStream = new DataOutputStream(
                conn.getOutputStream());
        outStream.write(params.toString().getBytes(CHARSET));
        // 发送文件数据
        if (files != null)
            for (Map.Entry<String, File> file : files.entrySet()) {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
                        + file.getValue().getName() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset="
                        + CHARSET + LINEND);
                // sb1.append("Content-Type: application/octet-stream;" +
                // LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(file.getValue().getPath(), options);
                Bitmap bmp = null;
                options.inJustDecodeBounds = false;
                long b = file.getValue().length();
                Log.i("file_length", "" + file.getValue().length());
                if (b > 300 * 1024) {
                    options.inSampleSize = (int) (b / (300 * 1024));


                    bmp = BitmapFactory.decodeFile(file.getValue().getPath(), options);
                } else {
                    bmp = BitmapFactory.decodeFile(file.getValue().getPath());
                }
                //   Log.i("bmp_length", "" + bmp.get);


                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                Log.i("bmp====>",""+baos.toByteArray().length);
                InputStream is = new ByteArrayInputStream(baos.toByteArray());


                //System.out.println("is");
                byte[] buffer = new byte[1024];
                int len = 0;
                int i = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                    //System.out.println("ttttt====="+(i++));

                }
                is.close();
                outStream.write(LINEND.getBytes());
            }

        // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // 得到响应码
        int res = conn.getResponseCode();
        Log.i("==res==", "" + res);
        StringBuilder sb2 = new StringBuilder();
        InputStream in = conn.getInputStream();

        if (res == 200) {
            int ch;
            while ((ch = in.read()) != -1) {
                sb2.append((char) ch);
            }
        }
        outStream.close();
        conn.disconnect();
        String yo = conn.getContentEncoding();
        String txt = new String(sb2.toString().getBytes("iso8859-1"), "utf-8");
        return txt;
    }


}